package org.rency.ues.engine.crypto.impl;

import org.rency.common.utils.security.X509CertUtils;
import org.rency.ues.common.UesDict;
import org.rency.ues.common.enums.EncryptType;
import org.rency.ues.domain.support.Certification;
import org.rency.ues.engine.crypto.Cryptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ${todo}
 *
 * @author: Created by user_rcy@163.com on 2016/8/1.
 * @version: V1.0.0
 * @since JDK 1.8
 */
public class CMSCryptor implements Cryptor{

    private static final Logger logger = LoggerFactory.getLogger(CMSCryptor.class);

    @Override
    public String getCryptorType() {
        return EncryptType.CMS.getCode();
    }

    @Override
    public byte[] decrypt(String enData, Object... args) {
        if(args == null || args.length != 1){
            logger.info("{}解密"+UesDict.CHINESE_PARAMETER_INVALID_MSG,this.getCryptorType());
            return null;
        }
        try {
            if(args[0] instanceof Certification){
                Certification certification = (Certification) args[0];
                return X509CertUtils.decryptCMS(enData, certification.getCertificate(), certification.getPrivateKey());
            }else{
                logger.info("{}解密"+UesDict.CHINESE_PARAMETER_INVALID_MSG,this.getCryptorType());
                return null;
            }

        } catch (Exception e) {
            logger.error("{}解密未知异常.",this.getCryptorType(),e);
            return null;
        }
    }

    @Override
    public String encrypt(byte[] plainData, Object... args) {
        if(args == null || args.length != 1){
            logger.info("{}加密"+UesDict.CHINESE_PARAMETER_INVALID_MSG,this.getCryptorType());
            return null;
        }
        try {
            if(args[0] instanceof Certification){
                Certification certification = (Certification) args[0];
                return X509CertUtils.encryptCMS(plainData, certification.getCertificate());
            }else {
                logger.info("{}加密"+UesDict.CHINESE_PARAMETER_INVALID_MSG,this.getCryptorType());
                return null;
            }
        } catch (Exception e) {
            logger.error("{}加密未知异常.",this.getCryptorType(),e);
            return null;
        }
    }
}
